<template>
  	<div class="">
    	<PageTitle :title="pageTitle"></PageTitle>
    	<div class="form-wrapper">
      		<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        		<el-form-item label="商品名称" prop="title">
          			<el-input v-model="ruleForm.title" placeholder="请输入商品名称"></el-input>
        		</el-form-item>
        		<el-form-item label="规格" prop="guageList" class="guage">
            		<template v-for="(item, index) in ruleForm.guageList">
						<el-popover
							placement="bottom"
							width="200"
							trigger="hover"
							:key="item.name"
						>
                			<ul style="list-style: none;padding:0;">
                  				<li style="margin-bottom: 10px;">
									<span style="display: inline-block;">名称：</span> {{ item.name }}
								</li>
                  				<li style="margin-bottom: 10px;">
									<span style="display: inline-block;">价格：</span> {{ item.price }} 元
								</li>
                  				<li style="margin-bottom: 10px;">
									<span style="display: inline-block;">加盟商价格：</span> <!-- {{ item.m_price }} 元 -->
									<div style="padding:5px">
										
										<div class="cont" v-if="Array.isArray(item.m_price)">
            								<div class="item" v-for="(it,index) in item.m_price" :key="index">
              									<div v-if="index === item.m_price.length-1">
                									{{it.price}}元>={{it.num}}箱
              									</div>
												<div v-else-if="index ===0">
													{{it.price}}元{{"<="+it.num}}箱
												</div>
												<div v-else>
													{{it.price}}元>={{it.num}}箱
												</div>
            								</div>
										</div>
										<div class="cont" v-else>
											{{item.m_price}}元
										</div>
									</div>
                  				</li>
                  				<li style="margin-bottom: 10px;">
									<span style="display: inline-block;">库存：</span> {{ item.stock }}
								</li>
                  				<li style="margin-bottom: 10px;">
                      				<span style="display: inline-block;">图片：</span>
                      				<img :src="item.imgUrl" style="display:inline-block;vertical-align: top;width:50px;height:50px">
                  				</li>
                			</ul>
                			<el-tag
							slot="reference"
							class="tag"
							@close="tagClose(item.id)"
							closable
							@click.native="dialogStandardsEdit(item.id, index)"
							>
                				{{ item.name }}
                			</el-tag>
              			</el-popover>
            		</template>
          			<el-button type="primary" @click="dialogStandardsAdd">添加</el-button>
       			</el-form-item>
				<el-form-item label="商品描述" prop="describe">
					<el-input v-model="ruleForm.describe" placeholder="请输入商品描述"></el-input>
				</el-form-item>
				<el-form-item label="优先级" prop="rise">
					<el-input v-model="ruleForm.rise" type="number" placeholder="请输入优先级数字"></el-input>
				</el-form-item>
        		<el-form-item label=" 视频(测试)" prop="">
					<UploadVideo
						:fileListArr="ruleForm.titleFileList"
						:fileListName="'titleFileList'"
						:fileMaxCount="1"
						@fileChange="fileChange"
					></UploadVideo>
       	 		</el-form-item>
				<el-form-item label="品牌LOGO (比例 1:1)" prop="logoFileList">
					<Upload
						:fileListArr="ruleForm.logoFileList"
						:fileListName="'logoFileList'"
						:fileMaxCount="1"
						@fileChange="fileChange"
					></Upload>
				</el-form-item>
				<el-form-item label=" 标题图片  (比例 1:5)" prop="titleFileList">
					<Upload
						:fileListArr="ruleForm.titleFileList"
						:fileListName="'titleFileList'"
						:fileMaxCount="1"
						@fileChange="fileChange"
					></Upload>
				</el-form-item>
				<el-form-item label=" 商品图片 (比例: 1:1)" prop="fileList">
					<Upload
						:fileListArr="ruleForm.fileList"
						:fileListName="'fileList'"
						:fileMaxCount="5"
						@fileChange="fileChange"
					></Upload>
				</el-form-item>
        		<!-- <el-form-item label="商品详情" prop="details" v-if="ruleForm.details"> -->
				<el-form-item label="商品详情" prop="details">
					<TinymceEditor @onChange="editorChange" :value="ruleForm.details"></TinymceEditor>
				</el-form-item>
				<el-form-item label="商品状态" prop="state">
					<el-select v-model="ruleForm.state" placeholder="前选择商品状态">
						<el-option label="上架" value="0"></el-option>
						<el-option label="下架" value="2"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="商品类型" prop="goodstype_id">
					<el-select v-model="ruleForm.goodstype_id" placeholder="请选择商品类别">
						<template v-for="(item, index) in goodsTypesArr">
							<el-option :label="item.class_name" :value="item.id" :key="index"></el-option>
						</template>
					</el-select>
				</el-form-item>
				<el-form-item label="运费" prop="freight">
					<el-input type="number" v-model="ruleForm.freight" placeholder="请输入运费" style="width:217px;">
						<template slot="append">元</template>
					</el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
					<el-button @click="$router.go(-1)">取消</el-button>
				</el-form-item>
      		</el-form>
    	</div>
    
		<el-dialog :visible="standardsAdd" custom-class="noX">
			<GoodsStandardsAdd @close="standardsAddClose"  @guageSuccess="guageAddSuccess"></GoodsStandardsAdd>
		</el-dialog>
		<el-dialog :visible="standardsEdit" custom-class="noX">
			<GoodsStandardsEdit @close="standardsEditClose" :id="guageId" :index="guageIndex" @guageSuccess="guageEditSuccess"></GoodsStandardsEdit>
		</el-dialog>
  	</div>
</template>

<script>
	import _ from 'lodash'
	import PageTitle from '@/components/pageTitle/PageTitle.vue'
	import Upload from '@/components/upload/Upload.vue'
	import UploadVideo from '@/components/uploadVideo/UploadVideo.vue'
	import GoodsStandardsAdd from '@/components/goodsStandardsAdd/GoodsStandardsAdd.vue'
	import GoodsStandardsEdit from '@/components/goodsStandardsEdit/GoodsStandardsEdit.vue'
	import TinymceEditor from '@/components/tinymceEditor/TinymceEditor.vue'
  	export default {
    	name: 'GoodsDetail',
		components: {
			PageTitle,
			Upload,
			UploadVideo,
			GoodsStandardsAdd,
			GoodsStandardsEdit,
			TinymceEditor
		},
    	async activated() {
      		this.$goTop()
      		let { data: { data } } = await this.$axios({
        		url: this.$api + '/v1/fication/frame',
        		method: 'GET',
				params: {
					size: 100,
					current: 1,
					state: 2
				}
      		})
      		this.goodsTypesArr = data.items
			if(this.$route.params.id != 'none') {
				this._get()
			}
    	},
		deactivated() {
			this.$destroy()
		},
    	data() {
      		return {
        		title: '',
        		goodsTypesArr: [],
        		ruleForm: {
					title: '',
					price: '',
					describe: '',
					Stock: '',
					details: '',
					state: '',
					goodstype_id: '',
					logoFileList: [],
					titleFileList: [],
					fileList: [],
					// 规格列表
					guageList: [],
					freight: '',
					rise: '',
					video: ''
        		},
        		rules: {
					title: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
					describe: [{ required: true, message: '请输入商品描述', trigger: 'blur' }],
					details: [{ required: true, message: '请编辑商品详情', trigger: 'blur' }],
					state: [{ required: true, message: '请选择商品状态', trigger: 'change' }],
					goodstype_id: [{ required: true, message: '请选择商品类型', trigger: 'change' }],
					logoFileList: [{ type: 'array', required: true, message: '请上传品牌LOGO' }],
					fileList: [{ type: 'array', required: true, message: '请上传商品图片' }],
					titleFileList: [{ type: 'array', required: true, message: '请上传标题图片' }],
					guageList: [{ type: 'array', required: true, message: '请添加商品规格' }],
					rise: [
						{ required: true, message: '请输入优先级', trigger: 'blur' },
						{
							validator(rule, value, callback) {
								const boolean = new RegExp(/^[1-9][0-9]*$/).test(value)
								if (!boolean) {
									return callback(new Error('请输入正整数'))
								}
								return callback()
							},
							trigger: 'blur'
						}
          			],
          			freight: [
            			{ required: true, message: '请输入运费', trigger: 'blur' },
						{
							validator(rule, value, callback) {
								const boolean = new RegExp(/^[1-9][0-9]*$/).test(value)
								if (!boolean) {
									return callback(new Error('请输入正整数'))
								}
								return callback()
							},
							trigger: 'blur'
						}
          			]
        		},
				standardsAdd: false,
				standardsEdit: false,
				standardsEditData: {},
        		// 查看规格详情用的Id
        		guageId: '',
				// 查看规格详情用的Index
				guageIndex: ''
      		};
    	},
    	computed: {
			pageTitle() {
				return this.$route.params.id == 'none' ? '商品添加' : '商品详情'
			},
			submitUrl() {
				return this.$route.params.id == 'none' ? this.$api + '/v1/goods/add' : this.$api + '/v1/goods/modify'
			},
			logoFileIdArr() {
				return this.ruleForm.logoFileList[0].id
			},
			titleFileIdArr() {
				return this.ruleForm.titleFileList[0].id
			},
			fileIdArr() {
				return this.ruleForm.fileList.map(item => {
					return item.id
				}).toString()
			},
			guageIdArr() {
				return this.ruleForm.guageList.map(item => {
					return item.id
				}).toString()
			}
    	},
    	methods: {
			// 监听富文本组件的自定义事件
			editorChange(e, data) {
				this.ruleForm.details = data
			},
			// 重置表单
			resetForm(formName) {
				this.$refs[formName].resetFields()
			},
      		// 如果是编辑页，请求数据的函数
      		async _get() {
        		let { data: { code, data } } = await this.$axios({
					url: this.$api + '/v1/goods/show',
					method: 'GET',
					params: {
						id: this.$route.params.id
					}
        		})
        		if (code === 0) {
					this.ruleForm.title = data.items[0].title
					this.ruleForm.price = data.items[0].price
					this.ruleForm.describe = data.items[0].describe
					this.ruleForm.Stock = data.items[0].Stock
					this.ruleForm.details = data.items[0].details
					this.ruleForm.state = data.items[0].state
					this.ruleForm.goodstype_id = data.items[0].goodstype_id
					this.ruleForm.freight = Number(data.items[0].freight)
					this.ruleForm.rise = Number(data.items[0].rise)
         			// 加载规格
          			this.ruleForm.guageList = []
          			data.gui.forEach(item => {
						this.ruleForm.guageList.push({
							id: item[0].id,
							name: item[0].name,
							price: item[0].price,
							m_price: JSON.parse(item[0].m_price),
							stock: item[0].stock,
							imgUrl: item[0].url
						})
					})
					  console.log(this.ruleForm.guageList)
          			// 加载logo
					this.ruleForm.logoFileList.push({
						id: data.log[0].picid,
						url: data.log[0].url
					})
					// 加载标题图片
					this.ruleForm.titleFileList.push({
						id: data.items[0].picid,
						url: data.items[0].url
					})
					// 加载详情图
					data.data.forEach(item => {
						this.ruleForm.fileList.push(item[0])
					})
        		}
      		},
			fileChange(data) {
				this.ruleForm[data.el] = data.arr
			},
      		// 提交表单
      		submitForm(formName) {
        		this.$refs[formName].validate(valid => {
          			if (!valid) {
            			return false
          			} else {
            			this._submit()
          			}
        		})
      		},
      		_submit: _.throttle(async function() {
        		let { data: { code, data } } = await this.$axios({
          			url: this.submitUrl,
          			method: 'POST',
          			data:{
						title: this.ruleForm.title,
						describe: this.ruleForm.describe,
						details: this.ruleForm.details,
						state: this.ruleForm.state,
						goodstype_id: this.ruleForm.goodstype_id,
						pice: this.titleFileIdArr,
						picture: this.fileIdArr,
						log_id: this.logoFileIdArr,
						hao_id: this.guageIdArr,
						up_id: 1,
						freight: this.ruleForm.freight,
						rise: this.ruleForm.rise,
						id: this.$route.params.id
					}
        		})
				if(code == 0) {
					this.$message.success(data)
					setTimeout(() => {
						this.$router.go(-1)
					}, 1500)
				}
      		}, 2000, {trailing: false}),
			dialogStandardsAdd() {
				this.standardsAdd = true
			},
      		dialogStandardsEdit(id, index) {
				this.guageId = id
				this.guageIndex = index
				this.$nextTick(() => {
					this.standardsEdit = true
				})
      		},
			standardsAddClose() {
				this.standardsAdd = false
			},
			standardsEditClose() {
				this.standardsEdit = false
			},
      		// 删除规格
      		async tagClose(tag) {
				// try{
				//   let {data: {data, msg, code}} = await this.$axios({
				//     url: this.$api + '/v1/gauge/except',
				//     method: 'POST',
				//     data: {
				//       id: tag
				//     }
				//   })
				//   if(code === 0) {
				//     this.$message.success(data)
				//   } else {
				//     this.$message.warning(data.message)
				//   }
				// }catch(e){
				//   this.$message({
				//     type: 'error',
				//     message: e
				//   })
				// }
				this.ruleForm.guageList = this.ruleForm.guageList.filter(item => {
					return item.id !== tag
				})
      		},
			guageAddSuccess(data) {
				this.ruleForm.guageList.push(data)
			},
			guageEditSuccess(data) {
				this.$set(this.ruleForm.guageList, data.index, data)
			}
   	 	}
  	}
</script>

<style lang='scss'>
  .form-wrapper {
    width:50%;
  }
  .guage {
    .tag {
      margin-right: 10px;
      cursor: pointer;
    }
  }
  .noX {
    .el-icon-close:before {
      content: ''
    }
  }
</style>
